import 'dart:async';
import 'second_page.dart';
import 'package:flutter/material.dart';
import 'package:umeng_analytics_plugin/umeng_analytics_plugin.dart';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> with WidgetsBindingObserver {
  String _platformVersion = 'Unknown';

  @override
  void initState() {
    super.initState();
    initPlatformState();
    WidgetsBinding.instance.addObserver(this);
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    if (state == AppLifecycleState.resumed) {
      UmengAnalyticsPlugin.event('didChangeShow');
    } else if (state == AppLifecycleState.paused) {
      UmengAnalyticsPlugin.event('didChangeHide');
    }
  }

  Future<void> initPlatformState() async {
    var result = await UmengAnalyticsPlugin.init(
      androidKey: '68c2654e9fb8d765d6ab06f8',
      iosKey: '5dfc5c034ca35748d1000c4c',
      ohosKey: '68c265059fb8d765d6ab06a5',
    );

    print('Umeng initialized.');
    if (!mounted) {
      return;
    }

    setState(() {
      _platformVersion = result ? 'OK' : 'ERROR';
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin example app'),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Text('Running on: $_platformVersion\n'),
              SizedBox(height: 20),
              Builder(builder: (BuildContext innerContext) {
                return ElevatedButton(
                  onPressed: () {
                    print('按钮点击，尝试导航到第二页');
                    try {
                      // 先记录事件，再执行导航
                      UmengAnalyticsPlugin.event('goto_second_page');
                      Navigator.push(
                        innerContext,
                        MaterialPageRoute(builder: (context) => SecondPage()),
                      ).then((_) {
                        print('从第二页返回');
                      });
                    } catch (e) {
                      print('导航失败: $e');
                    }
                  },
                  child: Text('跳转到第二页'),
                );
              }),
            ],
          ),
        ),
      ),
    );
  }
}
